package com.example.monitorsms.service;

import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.PowerManager;

import com.example.monitorsms.MainActivity;
import com.example.monitorsms.MyApp;
import com.example.monitorsms.utils.LogUtils;
import com.example.monitorsms.utils.StringUtils;

public class SmsRecevier extends BroadcastReceiver {

    public SmsRecevier() {
        super();
        LogUtils.e("SmsRecevier create");
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        LogUtils.e("SmsRecevier", "接收短信执行了.....");
        String dString = SmsHelper.getSmsBody(intent);
        String address = SmsHelper.getSmsAddress(intent);
        LogUtils.e("SmsRecevier", dString + "," + address);
        //阻止广播继续传递，如果该receiver比系统的级别高，
        //那么系统就不会收到短信通知了
        if (!StringUtils.isEmpty(dString) && dString.contains(MyApp.tipsOk)) {
            //屏幕唤醒
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            @SuppressLint("InvalidWakeLockTag")
            PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
                    | PowerManager.SCREEN_DIM_WAKE_LOCK, "BootBroadcastReceiver");
            wl.acquire();
            //屏幕解锁
            KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            KeyguardManager.KeyguardLock kl = km.newKeyguardLock("BootBroadcastReceiver");
            kl.disableKeyguard();
            if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
                Intent newIntent = new Intent(context, MainActivity.class);
                newIntent.setAction("android.intent.action.MAIN");
                newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(newIntent);
            }
            new Handler().postDelayed(() -> {
                MyApp.setPlayer();
                MyApp.setVibrate();
                LogUtils.e("SmsRecevier", "开始震动了");
            }, 5000);

            new Handler().postDelayed(() -> {
                LogUtils.e("SmsRecevier", "是否震动了");
                if (MyApp.vibrator.hasVibrator()) {
                    LogUtils.e("SmsRecevier", "是的震动了");
                    MyApp.vibrator.cancel();
                }
            }, 20000);
        }
        abortBroadcast();
    }
}
